package com.coocaa.treasure.view.picture;

import android.app.Dialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.coocaa.treasure.R;
import com.coocaa.treasure.util.Constants;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by xfk on 2015/9/9.
 */
public class FullScreenImageDialog extends Dialog {
    private Context mContext;
    private ImageView leftGuideImage;
    private ImageView rightGuideImage;
    private ImageView fullScreenImage;
    private FrameLayout frameLayout;
    private int curPos = 0;
    private List<String> imageUrlList;
    private Bitmap fullBitmap;
    private boolean isLoading = false;

    public FullScreenImageDialog(Context context) {
        super(context, R.style.Dialog_Fullscreen);
        mContext = context;
        createView();
    }

    public void refreshDialog(List<String> stringList, int currentIndex) {
        if(stringList == null || stringList.size() == 0 || currentIndex >= stringList.size()) {
            return;
        }

        curPos = currentIndex;
        imageUrlList = stringList;
        loadImage(stringList.get(curPos));
        refreshArrow();
    }

    private void refreshArrow() {
        if(curPos < imageUrlList.size() - 1) {
            rightGuideImage.setVisibility(View.VISIBLE);
        } else {
            rightGuideImage.setVisibility(View.INVISIBLE);
        }

        if(curPos > 0) {
            leftGuideImage.setVisibility(View.VISIBLE);
        } else {
            leftGuideImage.setVisibility(View.INVISIBLE);
        }
    }

    private void createView() {
        frameLayout = new FrameLayout(mContext);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        addContentView(frameLayout, layoutParams);

        fullScreenImage = new ImageView(mContext);
        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);

        frameLayout.addView(fullScreenImage, frameParams);

        leftGuideImage = new ImageView(mContext);
        leftGuideImage.setVisibility(View.INVISIBLE);
        leftGuideImage.setBackgroundResource(R.drawable.left_arrow);
        frameParams = new FrameLayout.LayoutParams(Constants.Div(35), Constants.Div(80));
        frameParams.leftMargin = Constants.Div(104);
        frameParams.topMargin = Constants.Div(542);
        frameLayout.addView(leftGuideImage,frameParams);

        rightGuideImage = new ImageView(mContext);
        rightGuideImage.setVisibility(View.INVISIBLE);
        rightGuideImage.setBackgroundResource(R.drawable.right_arrow);
        frameParams = new FrameLayout.LayoutParams(Constants.Div(35), Constants.Div(80));
        frameParams.leftMargin = Constants.Div(1720);
        frameParams.topMargin = Constants.Div(542);
        frameLayout.addView(rightGuideImage, frameParams);
    }

    Handler uiHandler = new Handler(Looper.getMainLooper());
    private void loadImage(final String url) {
        if(fullBitmap != null && !fullBitmap.isRecycled()) {
            Log.i("0909", "recycle bitmap");
            fullBitmap.recycle();
            Log.i("0909", "recycle: "+fullBitmap.isRecycled());
            fullBitmap = null;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = null;
                isLoading = true;

                Log.i("0909", "loadImage + ");
                String temp = "demo_resource/picture/"+url;
                AssetManager am = mContext.getResources().getAssets();
                try
                {
                    InputStream is = am.open(temp);
                    BitmapFactory.Options opt = new BitmapFactory.Options();

//                    //test
//                    opt.inJustDecodeBounds = true;
//                    opt.inSampleSize = computeSampleSize(opt, -1, Constants.Div(1920) * Constants.Div(1080));
                    BitmapFactory.decodeStream(is,null, opt);

                    opt.inJustDecodeBounds = false;
                    opt.inPreferredConfig = Bitmap.Config.RGB_565;
                    bitmap = BitmapFactory.decodeStream(is,null, opt);
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                    isLoading = false;
                }

                Log.i("0909", "bitmap size: "+getBitmapSize(bitmap));
                fullBitmap = resizeImage(bitmap, Constants.Div(1920), Constants.Div(1080));
                if(fullBitmap == null) {
                    fullBitmap = bitmap;
                } else {
                    if(bitmap != null)
                        bitmap.recycle();
                }

                Log.i("0909", "fullBitmap size: "+getBitmapSize(fullBitmap));
                uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (fullBitmap != null) {
                            fullScreenImage.setImageBitmap(null);
                            fullScreenImage.destroyDrawingCache();
                            fullScreenImage.setImageBitmap(fullBitmap);
                        } else {
                            Log.i("0908", "Image is null");
                        }

                        isLoading = false;
                    }
                });
            }
        }).start();
    }

    public int getBitmapSize(Bitmap bitmap){
        return bitmap.getRowBytes() * bitmap.getHeight()/1024/1024;
    }

    //使用Bitmap加Matrix来缩放
    public  Bitmap resizeImage(Bitmap bitmap, int w, int h)
    {
        if(bitmap == null)
            return null;
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        if(width < newWidth) {
            return null;
        }

        if(height < newHeight) {
            return null;
        }

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && isLoading == false) {
            if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                if(curPos < imageUrlList.size() - 1) {
                    curPos++;
                    loadImage(imageUrlList.get(curPos));
                    refreshArrow();
                }
            }

            if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                if(curPos > 0) {
                    curPos--;
                    loadImage(imageUrlList.get(curPos));
                    refreshArrow();
                }
            }

            if(keyCode == KeyEvent.KEYCODE_BACK) {
                this.dismiss();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void dismiss() {
        super.dismiss();

        frameLayout.removeAllViews();
        frameLayout.destroyDrawingCache();
        fullScreenImage.setImageBitmap(null);
        fullScreenImage.destroyDrawingCache();
        leftGuideImage.destroyDrawingCache();
        rightGuideImage.destroyDrawingCache();
        fullScreenImage = null;
        leftGuideImage = null;
        rightGuideImage = null;

        if(fullBitmap != null && !fullBitmap.isRecycled()) {
            Log.i("0909", "1 recycle bitmap");
            fullBitmap.recycle();
            System.gc();
        }

        fullBitmap = null;
    }
}
